package com.sky.interceptor;


import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.exception.UserNotLoginException;
import com.sky.properties.JwtProperties;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtTokenUserInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 获取请求头
        String token = request.getHeader(jwtProperties.getUserTokenName());

        // 判断有没有token
        if (token == null) {
            throw new UserNotLoginException(MessageConstant.USER_NOT_LOGIN);
        }

        try {
            // 有token就解析
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);

            // 获取id
            Integer id = (Integer) claims.get(JwtClaimsConstant.USER_ID);

            // 把id保存到ThreadLocal里面,方便后续的controller.service获取用户的id
            BaseContext.setCurrentId(id.longValue());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }
}
